import http.client
import json
import requests
import time
import random
from datetime import datetime, timedelta
import re

seq = 2747871
limit = 1000


def get_token():
    url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
    params = {
        'corpid': 'wwdd2b1373b42aca36',
        'corpsecret': "_0fN1LJz0Z_z9z0hOiss2R94RbgRK3Wl3WbZHE4_z8Y",
    }

    # 发送GET请求并获取响应
    response = requests.get(url, params=params)

    # 检查请求是否成功
    if response.status_code == 200:
        # 请求成功，可以处理响应数据
        data = response.json()
        token = data['access_token']
        return token
    else:
        # 请求失败，可以打印出错误信息
        print(f"Error: {response.status_code}")


def get_user(token, userid):
    url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get"
    # access_token = get_token()
    # external_userid = "wm4ru4CQAAD7AlAwn1-dtr3qUPAyCLFA"
    # 设置请求头（如果需要）
    headers = {
        'Content-Type': 'application/json',  # 如果你发送的是 JSON 数据
        # 'Authorization': 'Bearer YOUR_ACCESS_TOKEN'  # 如果需要认证
    }

    # 设置请求体（POST 请求的数据）
    data = {
        "access_token": token,
        "external_userid": userid
    }

    # 将字典转换为 JSON 字符串（如果需要）
    json_data = json.dumps(data)

    # 发送 POST 请求
    response = requests.get(url, headers=headers, params=data)

    # 检查响应状态码
    if response.status_code == 200:
        # print("请求成功")
        # 解析 JSON 响应内容
        response_user = response.json()
        return response_user
    else:
        return None
        # print(f"请求失败，状态码: {response.status_code}")
        # print("响应内容:", response.text)


def get_group(token, group_id):
    # 设置目标 URL
    url = f'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/get?access_token={token}'   # 设置请求头（如果需要）
    headers = {
        # 'Authorization': f'Bearer {token}',
        'Content-Type': 'application/json'  # 如果你发送的是JSON数据
    }

    # 设置请求体（POST 请求的数据）
    data = {
        "chat_id": group_id,
        "need_name": 0
    }

    # 将字典转换为 JSON 字符串（如果需要）
    json_data = json.dumps(data)

    # 发送 POST 请求
    response = requests.post(url, headers=headers, data=json_data)

    # 检查响应状态码
    if response.status_code == 200:
        # print("请求成功")
        # 解析 JSON 响应内容
        response_group = response.json()
        return response_group
        # print("响应数据:", response_data)
    else:
        return None
        # print(f"请求失败，状态码: {response.status_code}")
        # print("响应内容:", response.text)


def get_infor(seq, limit):
    # infor_list = []
    infor_dict = {}
    conn = http.client.HTTPConnection("116.62.120.28", 8888)
    payload = json.dumps({
        "seq": seq,
        "limit": limit,
        "timeout": 5
    })
    headers = {
        'Content-Type': 'application/json'
    }
    conn.request("POST", "/get_chat_data", payload, headers)
    res = conn.getresponse()
    data = res.read()
    result_data = json.loads(data.decode("utf-8")).get("data")
    if not result_data:
        return infor_dict, seq
    for infor in result_data:
        send_inf = infor.get("message")
        # print(send_infor)
        if send_inf:
            send_user = infor.get("message").get("from", None)
            send_group = infor.get("message").get("roomid", None)
            get_time = infor.get("message").get("msgtime", None)
            timestamp = get_time / 1000
            dt = datetime.fromtimestamp(timestamp)
            send_time = dt.strftime('%Y-%m-%d %H:%M:%S')

            if send_user.startswith("wo") or send_user.startswith("wm"):
                if infor.get("message").get("msgtype") == "text":
                    single_infor = infor.get("message").get("text").get("content")
                    if single_infor in infor_dict:
                        infor_dict[single_infor]["count"] += 1
                    else:
                        infor_dict[single_infor] = {"count": 1}
                        # infor_dict[single_infor]["count"] = 1
                        infor_dict[single_infor]["send_user"] = send_user
                        infor_dict[single_infor]["send_group"] = send_group
                        infor_dict[single_infor]["send_time"] = send_time
                    # infor_dict[single_infor] = {"send_user": send_user}
                    # infor_dict[single_infor] = {"send_group": send_group}

    result_seq = result_data[-1].get("seq")
    return infor_dict, result_seq


def send_group_msg(text_content, web_hook_url, mentioned_list):
    """
    发送微信群组机器人消息

    :param text_content: str, 消息内容
    :param web_hook_url: str, 群组机器人WebHook URL
    :param mentioned_list: list, 可选, userid列表，提醒群中的指定成员(@某个成员)，@all表示提醒所有人
    :param mentioned_mobile_list: list, 可选, 手机号列表，提醒手机号对应的群成员(@某个成员)，@all表示提醒所有人
    :return: tuple(bool, str), 返回一个元组，第一个元素为操作是否成功，第二个元素为成功或失败的消息
    """
    if mentioned_list is None:
        mentioned_list = []
    # if mentioned_mobile_list is None:
    #     mentioned_mobile_list = []

    msg = {
        "msgtype": "text",
        "text": {
            "content": text_content,
            "mentioned_list": mentioned_list,
            # "mentioned_mobile_list": mentioned_mobile_list
        }
    }

    try:
        response = requests.post(web_hook_url, json=msg)
        response.raise_for_status()  # 如果响应包含了一个HTTP错误状态码，则抛出异常
        result = response.json()

        if result.get('errmsg') == 'ok':
            return True, "Message sent successfully."
        else:
            return False, f"Failed to send message: {result.get('errmsg', 'Unknown error')}"

    except requests.exceptions.RequestException as e:
        return False, f"Request failed: {e}"

group_dict = {}
user_dict = {}
receive_dict = {}
group_infor_dict = {}
# 消息监听里面群通知的机器人地址。一二三四批次的
url1 = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=b6d51fce-df4f-49b1-802f-7cff1752ea5f"
url2 = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=61fe9216-035b-4bee-9117-0fbf4b44645a"
url3 = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=73ed428d-ff77-4b4c-8c29-e3055bdd720d"
url4 = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=cff6c9ff-0235-4698-b065-3e324e600468"
url_list1 = [url1, url2, url3, url4]
# 消息监听，四五批次
url5 ="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=2dadb428-f3b8-4385-9154-f2daa32787d5"
url6 ="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=7fdbf402-2c5e-417a-83bc-26e6810ca616"
url7 ="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=8101ecef-176a-490f-bd13-25fc2b7fc4f7"
url_list2 = [url5, url6, url7]
# 后面批次
url8 = ""
url9 = ""
url10 = ""

# 备用号的不通知，备用号新建了一个列表
people_list = ['莉莉安', '樱桃小丸子', '冬日暖阳', 'Amanda', '嘟妈', '豆豆爱拉豆豆', '季夏', '元宝团子', '周口爱尔眼科', '五金建材市场路店～赵姐', '快乐富足', '牧云', 'Mini', '洋洋子', '汤静', '农商银行小菠萝', '叫我yoyo嘛', '名艺装饰-欧工', 'ff8128', '拂晓', '最可爱的小米', 'AAA塑su蛋糕', '琳姐', '见山茶坊', '百变乐高马雪倩', '羊毛卷卷', '葱花也是花', 'momo', '翻斗花园壮壮妈', '架子鼓', '小小吃米糖', '笑口常开', 'choi樱桃', 'sarah', '一条美人余', '陶儿桃桃', 'amy', '此木思远', '俏妈咪高娟～产康 扎肚 塑形', '浩瀚妈妈', 'A莎莎美甲美睫', '鹿', '张美霞', '臭蛋奇遇记', '家有儿女', '草莓姜', '荔枝', 'Echo', '沈老师', '爱嘤嘤斯坦', 'Lisa', '初见', '叮当猫', '爱玛', '冯七七', 'xiao乔', '王珂', 'next', '顽固', 'hello', '鑫鑫妈妈', '森迪', '明明', '米粒儿', '李娇', '小豆子', '尹水机', '人生都是悲剧', '空谷幽兰', '芝士土豆妮', '壮壮妈', '莎莎美甲美睫', '欧工', '五金建材赵姐', '叫我yoyo妈', '俏妈咪', 'echo', '古陈蕊', '初喻', '雪蓉', '胡桃夹子', '月印', '朵朵妈妈', '幸运星', 'wuhu芜湖', '美果鲜', '墩墩是只猫', '鱼可可', '扶桑', 'emo', '火山轰鸣', '黑灯', '慢半拍', '不要安办登', '旺旺小仙', '童谣', '噗叽GO', '冰糖炖雪梨', 'Nuyoah', '爱思岚', '月沉', '向着光', '糖醋里脊', 'ting', 'doja', 'Mr.How', 'Emily', 'Candy', '🧸ྀི', 'iiivy', '得鹿梦鱼', '四季予家', '丸子🍡', 'Ariel', 'yees', '幻', 'の', '许妃儿', '333Polar', 'YYDS！', 'Elly', '滴滴答答', '🔆', '丽丽呀', 'potato', '好运来', '开心每一天', 'hii', 'miraitowa', 'Ava']
five_list = ['琪姐姐', '人生都是悲剧', '迪士尼的唐老鸭', '尹水机', '红玫瑰', '有限维度看春秋', '心想事成', '芝士土豆妮', '空谷幽兰', '丹妮', '爱吃巧克力', '平平安安', '沙滩上的小鱼人', '暮光下的尘埃', '古陳芯']+['ting', 'doja', 'Mr.How', 'Emily', 'Candy', '🧸ྀི', 'iiivy', '得鹿梦鱼', '四季予家', '丸子🍡', 'Ariel', 'yees', '幻', 'の', '许妃儿', '333Polar', '\xa0YYDS！', 'Elly', '滴滴答答', '🔆', '丽丽呀', 'potato', '好运来', '开心每一天', 'hii', 'miraitowa', 'Ava', 'leean']
people_list.extend(five_list)
# 第五六批次的群列表
group5_list = [f"W{i}" for i in range(201, 226)]
# 第一二三四批次群列表
group_list1 = [f"E{i}" for i in range(220, 238)]
group_list2 = [f"E{i}" for i in range(389, 390)]
group_list3 = [f"E{i}" for i in range(600, 680)]
# group_list4 = [f"E{i}" for i in range(650, 679)]
group_list5 = [f"E{i}" for i in range(400, 439)]
group_list6 = [f"E{i}" for i in range(460, 479)]
group1_list = group_list1 + group_list2 + group_list3 + group_list5 + group_list6
# for i in range(1):
time_first = datetime.now()
token = ""
try:
    while 1:
        user_name = ""
        group_name = ""
        group_owner = ""

        # 第一次获取当前时间

        time_second = datetime.now()
        time_difference = time_second - time_first
    # 检查时间差是否超过一小时
        if time_difference > timedelta(hours=1):
            time_first = time_second
            # 执行相应的操作
            token = get_token()
        else:
            if token == "":
                token = get_token()
        # token = "6YTHd_lHgYomEOgmpEq-F4UmYYDXsy-8uMJzk5tfisMDA99ASNyyQKe0TmgIFWCbFOhy9f-W4hWVZKq2A5phhXzRIt3iL93Nz4sYpWftCi6Pf6JAPikm1cE6K5S_VuZIMiaeYylE5piOHnmKTHgsAFZ3CpNEIRERANX713XipCTFBgfI5nYKxN5HUVlfwsTin7oI8E8gcUnbofqD2s_Img"
        one_infor, new_seq = get_infor(seq, limit)
        print(len(one_infor), one_infor)
        for k, v in one_infor.items():
            user_name = ""
            group_name = ""
            group_owner = ""
            random_value = ""
            if v.get("count") == 1:
                if v.get("send_user") in user_dict.keys():
                    user_name = user_dict[v.get("send_user")]
                    if user_name in people_list:
                        continue
                else:
                    user_infor = get_user(token, v.get("send_user"))
                    # print(f"user_infor::{user_infor}")
                    if user_infor:
                        if user_infor.get("errcode") == 0:
                            user_name = user_infor.get("external_contact").get("name")
                            user_dict[v.get("send_user")] = user_name
                            if user_name in people_list:
                                continue
                if v.get("send_group") in group_dict.keys():
                    group_name = group_dict[v.get("send_group")]
                    group_owner = group_infor_dict[group_name]
                else:
                    group_infor = get_group(token, v.get("send_group"))
                    # print(f"group_infor::{group_infor}")
                    if group_infor:
                        if group_infor.get("errcode") == 0:
                            group_name = group_infor.get("group_chat").get("name")
                            group_owner = group_infor.get("group_chat").get("owner")
                            group_dict[v.get("send_group")] = group_name
                            group_infor_dict[group_name] = group_owner
                time_flag = v.get("send_time")
                # 分发群消息通知
                match = re.search(r'[a-zA-Z]\d{3,4}', group_name)
                # 第五批次的群列表
                # group5_list = [f"W{i}" for i in range(141, 170)]
                if match:
                    if match.group() in group5_list:
                        random_value = random.choice(url_list2)
                    elif match.group() in group1_list:
                        random_value = random.choice(url_list1)
                    else:
                        continue
                else:
                    continue
                    # else:
                    #     random_value = random.choice(url_list1)
                # else:
                #     random_value = random.choice(url_list1)
                # 将要发送的消息内容是
                send_infor = "用户名：" + user_name + "\n" + "群聊名称：" + group_name + "\n" + "发送内容：" + k + "\n" + "发送时间：" + time_flag
                # print(send_infor)
                # 随机取列表中的一个机器人地址进行发送
                # random_value = random.choice(url_list)
                send_flag, result_infor = send_group_msg(send_infor, random_value, [group_owner])
                if not send_flag:
                    print(result_infor)
                    time.sleep(5)
                    random_value = random.choice(url_list1)
                    send_flag, result_infor = send_group_msg(send_infor, random_value, [group_owner])

        time.sleep(5)
        if seq <= new_seq + 300:
            time.sleep(60)
        seq = new_seq
        print(f"seq:{seq}")
except Exception as e:
    group_owner = ""
    error_message = str(e)
    send_flag, result_infor = send_group_msg(error_message, url1, [group_owner])


